package com.epam.ws.anatomist.validation;

import java.util.Map;

import junit.framework.AssertionFailedError;

import org.apache.log4j.Logger;
import org.custommonkey.xmlunit.XMLAssert;
import org.custommonkey.xmlunit.exceptions.XpathException;
import org.w3c.dom.Document;

import com.epam.ws.anatomist.common.exception.ErrorMessages;
import com.epam.ws.anatomist.common.exception.XmlAssertionException;

public class XmlAssert
{

	private static final Logger LOGGER = Logger.getLogger(XmlAssert.class);

	private static final String XPATH_EVALUATION_PASSED_MESSAGE = "Check Xpath evaluation - Passed";

	private static final String XPATH_VALUE_CHECKING_INFO_MESSAGE = "XPath {%1$s} evaluates to [%2$s] and equals to expected value";

	/**
	 * Validate XML document by provided groups of XPATH/Value
	 * 
	 * @param data - Map(XPATH, Value)
	 * @param response
	 */
	public static void assertXpathEvaluatesTo(Map<String, String> data, Document response)
	{
		String xpath = null;
		if (data == null || response == null)
		{
			throw new XmlAssertionException(ErrorMessages.XPATH_ASSERTION_PARAMETERS_ERROR);
		}
		try
		{
			for (String key : data.keySet())
			{
				xpath = key;
				XMLAssert.assertXpathEvaluatesTo(data.get(key), xpath, response);
				LOGGER.debug(String.format(XPATH_VALUE_CHECKING_INFO_MESSAGE, key, data.get(key)));
			}

			LOGGER.info(XPATH_EVALUATION_PASSED_MESSAGE);
		}
		catch (XpathException e)
		{
			LOGGER.error(ErrorMessages.XPATH_EVALUATION_ERROR);
			throw new XmlAssertionException(ErrorMessages.XPATH_EVALUATION_ERROR, e);
		}
		catch (AssertionFailedError e)
		{
			LOGGER.error(String.format(ErrorMessages.XPATH_VALUE_CHECKING_ERROR, xpath), e);
			throw new XmlAssertionException(e);
		}
	}

}
